import re

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.ausers.models import User
from meiduo_mall.settings.dev import logger
#3.判断手机号是否重复
from utils.response_code import RETCODE
#用户中心

class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        return render(request,"user_center_info.html")

#退出
class LogoutView(View):
    def get(self,request):
        from django.contrib.auth import logout
        #退出 登陆logoutd
        logout(request)
        #调到login.html
        response=redirect(reverse("users:login"))
        #删除cookie
        response.delete_cookie("username")
        return response
    #登陆页显示 功能
class LoginView(View):
    def get(self,request):
        return render(request,"login.html")
    def post(self,request):
        #接受参数
        username=request.POST.get("username")
        password=request.POST.get("password")
        remembered=request.POST.get("remembered")
        #3.解析校验 判空 和判断正则
        #数据交互username,password django自带的认证函数
        from django.contrib.auth import authenticate,login
        user=authenticate(username=username,password=password)
        #登陆失败
        if user is None:
            return render(request,"login.html",{"account_errmsg":"用户名或密码错误"})
        #5保持登录状态
        login(request,user)
        #6,记住登陆
        if remembered!="on":
            #不记住---会话结束  就失效了
            request.session.set_expiry(0)
        else:
            #记住----两周
            request.session.set_expiry(None)
        #next 记录上一个页面的路由
        next=request.GET.get("next")
        if next:
            response=redirect(next)
        else:
            #跳转首页
            response=redirect(reverse("contents:index"))
        response.set_cookie("username",username,max_age=14*3600*24)
        return response




class MobileCountView(View):
    def get(self,request,mobile):
        #1.接收参数mobile
        #2.校验参数 判空 判正则
        #3.数据库查询个数
        try:
            count=User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden("手机号不存在")
        #4.返回前端个数
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})



#2.判断用户名重复
class UsernameCountView(View):
    def get(self,request,username):
        #1.接收用户名username
        #2.校验判空 和正则
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$",username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        #3.逻辑数据库查询
        try:
            from apps.ausers.models import User
            count=User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden("不存在")
        #4.返回给前段json
        from utils.response_code import RETCODE
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"查询成功","count":count})


class RegisterView(View):
    def get(self,request):
        return render(request,"register.html")
        #JsonResponse传递列表list safe=False;
        # data_dict=[{
        #     "a":10,
        #     "b":20,
        #     "c":20,
        # }]
        # return http.JsonResponse(data_dict,safe=False)

    #注册功能
    def post(self,request):
        #1.接收参数request.POST
        username=request.POST.get("username")
        password=request.POST.get("password")
        password2=request.POST.get("password2")
        mobile=request.POST.get("mobile")
        allow=request.POST.get("allow")
        sms_code=request.POST.get("msg_code")
        #2.校验参数
        #2.1判空
        if not all([username,password,password2,mobile]):
            return http.HttpResponseForbidden("参数不能为空")
        #1.用户名------判空，正则校验，是否重复
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$",username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        #密码-----判空http.HttpResponseForbidden("参数不能为空")，正则校验，
        if not re.match(r"[a-zA-Z0-9_-]{8,20}$",password):
            return http.HttpResponseForbidden("请输入8-20个字符的用户名")
        #确认密码----判空，判断是否相等
        if password!=password2:
            return http.HttpResponseForbidden("两次密码不一致")
        #手机号-------判空，正则校验 ，是否重复
        if not re.match(r"1[3456789]\d{9}$",mobile):
            return http.HttpResponseForbidden("手机号格式不正确")
        #5.图形验证码
        #6.短信验证码
        #7.同意“美多商城用户使用协议”判断是否选中
        if allow!="on":
            #没有勾选gku8
            return http.HttpResponseForbidden("请勾选协议")
        #6.短信验证码
        #导报
        #链接
        sms_redis_client=get_redis_connection('sms_code')

        #取值
        sms_redis_code=sms_redis_client.get("sms_%s"%mobile)

        #判断
        if sms_redis_code is None:
            return render(request,"register.html",{"sms_code_errmsg":"无效的短信验证码"})
        #千万注意：redis取出来的bytes.decode()
        if sms_code!=sms_redis_code.decode():
            return render(request,"register.html",{"sms_code_errmsg":"短信验证码验证失败"})
        #注册用户django自带的User的函数create_user()
        try:
            from apps.ausers.models import User
            user=User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            logger.info(e)
            return render(request,"register.html",{"register_message":"注册失败"})
        #返回响应
        # return redirect("/")
        #保持登陆状态
        from django.contrib.auth import login
        login(request,user)
        return redirect(reverse("contents:index"))